package org.zhuxian.cn.task;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.concurrent.TimeUnit;

@Component
public class FileCleanupTask {

    @Value("${file.temp-dir:/tmp/images}")
    private String tempDir;

    @Scheduled(fixedRate = 10, timeUnit = TimeUnit.MINUTES)
    public void cleanExpiredFiles() {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(tempDir), "*.jpg")) {
            for (Path file : stream) {
                String fileName = file.getFileName().toString();
                String[] parts = fileName.split("_");
                if (parts.length < 2) continue;

                long timestamp;
                try {
                    timestamp = Long.parseLong(parts[1].split("\\.")[0]);
                } catch (NumberFormatException e) {
                    continue;
                }

                long currentTime = Instant.now().toEpochMilli();
                if (currentTime - timestamp > TimeUnit.MINUTES.toMillis(10)) {
                    Files.deleteIfExists(file);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}